import pygame
import random

# 初始化 Pygame
pygame.init()

# 定义常量
WIDTH, HEIGHT = 800, 600
CARD_WIDTH, CARD_HEIGHT = 80, 100

# 创建窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("羊了个羊简易版")

# 加载背景图片
background_image = pygame.image.load('t.png')
background_image = pygame.transform.scale(background_image, (WIDTH, HEIGHT))

# 卡片类型和对应的图片
card_types = ['🐏', '🐑', '🐐']
card_images = {
    '🐏': pygame.image.load('tile.png'),
    '🐑': pygame.image.load('win.png'),
    '🐐': pygame.image.load('back.png')
}
# 调整卡片图片大小
for key in card_images:
    card_images[key] = pygame.transform.scale(card_images[key], (CARD_WIDTH, CARD_HEIGHT))

# 初始化游戏板
num_cards = 18
game_board = []
for _ in range(num_cards):
    card_type = random.choice(card_types)
    x = random.randint(0, WIDTH - CARD_WIDTH)
    y = random.randint(0, HEIGHT - CARD_HEIGHT - 150)
    game_board.append((card_type, x, y))

# 卡槽
num_slots = 7
slots = []
slot_x_start = (WIDTH - num_slots * (CARD_WIDTH + 10)) // 2
slot_y = HEIGHT - CARD_HEIGHT - 50

# 字体设置
font = pygame.font.Font(None, 36)


def draw_card(card_type, x, y):
    screen.blit(card_images[card_type], (x, y))


def draw_slot(slot_type, index):
    x = slot_x_start + index * (CARD_WIDTH + 10)
    if slot_type:
        screen.blit(card_images[slot_type], (x, slot_y))


# 游戏主循环
running = True
while running:
    # 绘制背景图片
    screen.blit(background_image, (0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = event.pos
            for i, (card_type, x, y) in enumerate(game_board):
                if x <= mouse_x <= x + CARD_WIDTH and y <= mouse_y <= y + CARD_HEIGHT:
                    if len(slots) < num_slots:
                        existing_index = next((i for i, slot in enumerate(slots) if slot == card_type), None)
                        if existing_index is not None:
                            matching_count = slots.count(card_type)
                            if matching_count == 2:
                                # 移除三个相同的卡片
                                slots = [slot for slot in slots if slot != card_type]
                            else:
                                slots.append(card_type)
                        else:
                            slots.append(card_type)
                        # 从游戏板移除卡片
                        del game_board[i]
                    break

    # 绘制游戏板上的卡片
    for card_type, x, y in game_board:
        draw_card(card_type, x, y)

    # 绘制卡槽
    for i, slot_type in enumerate(slots):
        draw_slot(slot_type, i)
    for i in range(len(slots), num_slots):
        draw_slot(None, i)

    pygame.display.flip()

pygame.quit()
